package com.zhanghe.study.thread.test_001;

/**
 * 写加锁，读不加锁会出现脏读
 *
 * @author: zhanghe
 * @date: 2020/6/22 15:37
 */
public class TestDirtyRead {

    private String name;

    private int blance;

    public synchronized void set(String name, int blance) {
        this.name = name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.blance = blance;
    }

    public /*synchronized*/ int getBlance(String name){
        return this.blance;
    }

    public static void main(String[] args) {
        TestDirtyRead testDirtyRead = new TestDirtyRead();
        Thread t1 = new Thread(()->{
            testDirtyRead.set("张三",100);
        });
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(testDirtyRead.getBlance("张三")); // 0
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(testDirtyRead.getBlance("张三")); //100

    }
}
